
layui.define(['jquery', 'form', 'layer', 'element','table','laydate'], function(exports) {
    var $ = layui.jquery,
        form = layui.form,
        layer = layui.layer,
        element = layui.element,
        table = layui.table,
        laydate = layui.laydate;

    laydate.render({
        elem: '#startday'
    });

    laydate.render({
        elem: '#endday'
    });

    laydate.render({
        elem: '#_startday'
    });

    laydate.render({
        elem: '#_endday'
    });
    var jsonarray='';
    var housejsonarray='';
    var housepaydata='';
    var should_pay = 0;
    var total_pay = 0;
    var pay_no = '';
    var iCount = '';
    var get_pay = '';
    var iCountBox = '';
    var emptystr = "[]";
    var emptyjsonarray = eval('(' + emptystr + ')');
    var temitemstr = "[]";
    var temitemjsonarray = eval('(' + temitemstr + ')');
    var com_id=GetSessionKeyVale('com_id');
    // var name=GetSessionKeyVale('name');
    $.bootstrapLoading.start({loadingTips: "正在加载基础信息，请等待..."});
    var name='管理员';
    // var username=GetSessionKeyVale('username');
    var username='admin';
    var drugdata = '';
    setTimeout(function (){
        drugdata = LoadDrug();
        $.bootstrapLoading.endLoading();
    },200);
    var index = 0;
    var rowindex = 0;
    form.render('select', 'sel_srf');
    var checkjsonstr="[]";
    var checkjsonarray = eval('('+checkjsonstr+')');
    var start = '';
    var isadd = '';     //0—允许添加收费项目；1—不允许添加收费项目
    var ispay = '';     //0—首次新增单据；1—单据已保存；2—单据已收费；3—单据已作废
    var base_pro_id = '';
    var sWxpay_id = '';
    var sAlipay_id = '';
    var payType = '';
    var qte_name = '';
    var bill_type_id = '';
    $('.date').val(GetDate());
    renderPro(emptyjsonarray);
    renderJm();
    renderClose();
    renderPayType('qte');
    renderPayType('cqte');
    renderItemType('item_type_id');
    form.render('select', 'sel_target');
    form.render('select', 'sel_status');
    // rendermemberevent();

    $("#savePay").attr('disabled',true);
    $("#editPay").attr('disabled',true);
    $("#StopTem").attr('disabled',true);
    $("#PrintTem").attr('disabled',true);
    $("#addTemItem").attr('disabled',true);
    $("#btnPay").attr('disabled',true);
    $("#Audit").attr('disabled',true);


    var heigth_screen = window.screen.height;    //获取整个屏幕的分辨率\
    var gg = $("#mainFrame", parent.document).height();
    heigth_screen = window.screen.height - 100;
    var aa = ''

    function renderdruglist(jsonarray){
        //TODO 渲染药品表格
        table.render({
            elem: '#DrugList',
            //limits: [3,5,10]
            //,limit: 10 ,//每页默认显示的数量
            // height:500,
            cols: [
                [ {
                    field: 'drugId',title: '药品ID',width:'15%'
                }, {
                    field: 'drugName',title: '药品名称'
                }, {
                    field: 'drugSpecifications',title: '药品规格'
                },{
                    field: 'drugUnit',title: '药品单位'
                },{
                    field: 'priceIn',title: '入库价'
                }]
            ],
            data:jsonarray,
            event: true,
            page: false,
            done: function (d) {
                // $("[data-field='id']").css('display','none');
                // $("[data-field='py']").css('display','none');
                // $("[data-field='type']").css('display','none');

            }
        });
    }

    function renderdrugevent(){
        //TODO 渲染药品表格事件
        //监听行单击事件（单击事件为：rowDouble）
        table.on('row(drugevent)', function(obj){
            var data = obj.data;
            $("#drug_name").val(data.drugName);
            $("#drug_specifications").val(data.drugSpecifications);
            $("#drug_id").val(data.drugId);
            $("#drug_unit").val(data.drugUnit);
            $("#in_price").val(data.priceIn).focus();
            $("#drug_jm").val('');
            $("#FormDrug").css('display','none');
        });
    }




    function renderPro(jsonarray){
        //TODO 渲染入库药品明细（外表）启用编辑框和删除
        table.render({
            elem: '#InStorageList',
            limits: [3,5,10],
            height:window.screen.height - 120
            ,limit: Number.MAX_VALUE ,//每页默认显示的数量
            totalRow: true,
            toolbar: '#HousePayTool',
            cols: [
                [ {type:'numbers'},
                    {
                    field: 'drugId',title: '药品ID',sort: true
                }, {
                    field: 'drugName',title: '药品名称',sort: true
                }, {
                    field: 'drugSpecifications',title: '药品规格'
                },{
                    field: 'drugUnit',title: '药品单位'
                },{
                    field: 'priceIn',title: '入库价'
                },{
                    field: 'drugNumber',title: '入库数量'
                }, {
                    field: 'remark',title: '备注',edit:'text'
                },
                    {
                    field: 'del',width:'10%',title: '操作',fixed: 'right',align:'center',
                    templet:function(d){
                        return '<a title="删除药品"><span class="layui-btn layui-btn-disabled layui-btn-xs delitem" style="cursor: pointer" lay-event="del">删除药品</span></a>'
                    }
                }
                ]
            ],
            data:jsonarray,
            event: true,
            page: false,
            loading: true, //请求数据时，是否显示loading
            done: function (d) {
                // $("[data-field='tem_item_id']").css('display','none');
            }
        });
    }


    function renderPro2(jsonarray){
        //TODO 渲染入库药品明细（外表）禁用编辑框和删除
        table.render({
            elem: '#InStorageList',
            limits: [3,5,10],
            height:window.screen.height - 120
            ,limit: Number.MAX_VALUE ,//每页默认显示的数量
            totalRow: true,
            toolbar: '#HousePayTool',
            cols: [
                [ {type:'numbers'},
                    {
                        field: 'drugId',title: '药品ID',sort: true
                    }, {
                    field: 'drugName',title: '药品名称',sort: true
                }, {
                    field: 'drugSpecifications',title: '药品规格'
                },{
                    field: 'drugUnit',title: '药品单位'
                },{
                    field: 'priceIn',title: '入库价'
                },{
                    field: 'drugNumber',title: '入库数量'
                }, {
                    field: 'remark',title: '备注',edit:'text'
                }, {
                        field: 'del',width:'10%',title: '操作',fixed: 'right',align:'center',
                        templet:function(d){
                            return '<a title="删除费用"><span class="layui-btn layui-btn-disabled layui-btn-xs delitem" style="color:#FFF;background-color:#ccc">删除费用</span></a>'
                        }
                    }
                ]
            ],
            data:jsonarray,
            event: true,
            page: false,
            loading: true, //请求数据时，是否显示loading
            done: function (d) {
                // $("[data-field='tem_item_id']").css('display','none');
            }
        });
    }


    function renderTemTable(housejsonarray){
        //TODO 渲染单据数据（上表）
        table.render({
            elem: '#TemTable',
            height:220,
            limits: [3,5,10]
            ,limit: Number.MAX_VALUE, //每页默认显示的数量
            // ,toolbar: '#UnProTool',
            // totalRow: true,
            cols: [
                [
                    // {
                    //     field: 'id',title: 'ID',width:'8%'
                    // },
                    {
                    field: 'serialNo',title: '单据号',sort: true
                }, {
                    field: 'type',title: '类型'
                },{
                    field: 'status',title: '状态',templet: function (d) {
                        if ( d.status == "1" ) {  // 0 为已保存 1 为收费  2为已作废
                            return '<span class="layui-btn layui-btn-warmfont layui-btn-xs">已保存</span>';
                        } else if( d.status == "2" ){
                            return '<span class="layui-btn layui-btn-online layui-btn-xs">已审核</span>';
                        } else if( d.status == "-1" ){
                            return '<span class="layui-btn layui-btn-disabled layui-btn-xs">已作废</span>';
                        }
                    }
                }, {
                        field: 'gmtCreate',title: '创建时间'
                    },{
                    field: 'operator',title: '创建者'
                }]
            ],
            data:housejsonarray,
            event: true,
            page: false,
            loading: true //请求数据时，是否显示loading
        });
    }


    function renderTemDetailTable(housejsonarray){
        //TODO 渲染单据明细数据(下表)
        table.render({
            elem: '#TemDetailTable',
            // width:630,
            height:300,
            limits: [3,5,10]
            ,limit: Number.MAX_VALUE, //每页默认显示的数量
            totalRow: true,
            cols: [
                [   {type:'numbers'},
                    // {
                    //     field: 'tem_item_id',title: '开始日期'//,sort: true
                    // },
                    {
                        field: 'drugName',title: '药品名称',totalRowText: '合计',sort: true
                    }, {
                    field: 'drugSpecifications',title: '规格'
                }, {
                    field: 'drugUnit',title: '单位'
                }, {
                    field: 'price',title: '入库价'
                }, {
                    field: 'number',title: '入库数量'
                }, {
                    field: 'price',title: '金额',templet: function (d) {
                        return (parseFloat(d.price) * parseFloat(d.number)).toFixed(2)
                        // return (parseFloat(d.price) * parseFloat(d.number)).toFixed(2)
                    },totalRow: true,sort: true
                },  {
                    field: 'remark',title: '备注'
                }
                ]
            ],
            data:housejsonarray,
            event: true,
            page: false,
            loading: true //请求数据时，是否显示loading
        });
    }




    function renderProevent(){
        //TODO 渲染费用明细表格事件
        table.on('tool(InStorageList)', function(obj){
             if( obj.event === 'del' ){
                layer.confirm('确认删除么', function(index){
                    var data = obj.data;
                    for(var i = 0;i<temitemjsonarray.length;i++){
                        if( data.drugId == temitemjsonarray[i].drugId){
                            temitemjsonarray.splice(i, 1);
                            obj.del();
                        }
                    }
                    layer.msg('删除成功', {
                        icon: 1,
                        time: 1000
                    });
                    layer.close(index);
                });
            }
        });
        table.on('toolbar(InStorageList)', function(obj){
            // datajsonarray.length = 0;
            // datajsonarray = getData();
            // var checkPay = table.checkStatus(obj.config.id);
            if (obj.event === 'btnPay'){
                if(sumpay() == 'NaN' || sumpay() == 0){
                    layer.msg('项目费用有误，请检查', {
                        icon: 5,
                        time: 1000
                    });
                }else{
                    $('.should_pay').text(sumpay());
                    $('#should_pay').val(sumpay());
                    if(CheckComplete()==true){
                        if( temitemjsonarray.length == 0){
                            layer.msg('无收费项目', {
                                icon: 2,
                                time: 1000
                            });
                        }else{
                            $.ajax(
                                {
                                    type: "post",
                                    async: false,
                                    url: "/notes/getFirstBillNo",
                                    data: {
                                        receiveUserName:GetSessionKeyVale('name'),
                                        billTypeId:bill_type_id,
                                        status:1
                                    },
                                    success:function (data) {
                                        if(data.status == 200){
                                            var data = data.data;
                                            if( data == null){
                                                $('.bill').hide();
                                                $('#billno').val('')
                                            }else{
                                                $('.bill').show();
                                                $('#billno').val(data.billNo).attr('disabled',true).attr('billid',data.id);
                                            }
                                        }else{
                                            layer.msg(data.msg, {
                                                icon: 2,
                                                time: 1000
                                            });
                                        }
                                    }
                                }
                            );
                            if( ispay == 0 ){
                                //TODO 新增单据
                                if( addtem() == true ){
                                    $("#drug_jm").attr('disabled',true);
                                    $("#in_price").attr('disabled',true);
                                    $("#drug_number").attr('disabled',true);
                                    $("#savePay").attr('disabled',true);
                                    isadd = 1;
                                    ispay = 1;
                                    renderPro2(temitemjsonarray);
                                    $("#editPay").removeAttr('disabled');
                                    $("#StopTem").removeAttr('disabled');
                                    $("#PrintTem").attr('disabled',true);
                                    // $('#qte').val('');
                                    // form.render('select', 'qte');
                                    // $('#PayForm').modal('show');
                                    // $(".get_pay").val('').removeAttr('disabled');
                                    // $(".back_pay").val(0);
                                    // disQte();
                                }
                            }else if ( ispay == 1 ){
                                //TODO 修改保存单据
                                if( edittem() == true ){
                                    $("#target_id").attr('disabled',true);
                                    form.render('select', 'sel_target');
                                    $("#contacts").attr('disabled',true);
                                    $("#phone").attr('disabled',true);
                                    $("#tem_house_no").attr('disabled',true);
                                    $("#remark").attr('disabled',true);
                                    $("#savePay").attr('disabled',true);
                                    renderPro2(temitemjsonarray);
                                    $("#editPay").removeAttr('disabled');
                                    $("#StopTem").removeAttr('disabled');
                                    $("#PrintTem").attr('disabled',true);
                                    isadd = 1;
                                    ispay = 1;

                                    $('#qte').val('');
                                    form.render('select', 'qte');
                                    $('#PayForm').modal('show');
                                    $(".get_pay").val('').removeAttr('disabled');
                                    disQte();
                                }
                            }else if ( ispay == 2 ){
                                layer.msg('此单据已经收费', {
                                    icon: 5,
                                    time: 1000
                                })
                            }else if ( ispay == 3 ){
                                layer.msg('此单据已作废', {
                                    icon: 5,
                                    time: 1000
                                })
                            }
                        }
                    }else{
                        return false;
                    }
                }

            }else if( obj.event === 'addTemItem' ){
                //TODO 增加收费项目
                if( isadd == 0){
                    $('#AdditemForm').modal('show');
                    $('#tem_item_name').focus().val('');
                }else{
                    layer.msg('请在编辑状态下添加项目', {
                        icon: 5,
                        time: 1000
                    })
                }
            }
        });
    }


    function renderTemTableevent(){
        //TODO 渲染住户表格（上表）事件
        table.on('row(TemTable)', function(obj){
            //TODO 单击查看未缴费（下表）数据
            // CheckSession();
            housepaydata.length = 0;
            var data = obj.data;
            $.ajax(
                {
                    type: "get",
                    async: false,
                    url: "/drug-input-output/listBySerialNO",
                    data: {
                        serialNo:data.serialNo
                        // startday:$("#startday").val(),
                        // endday:$("#endday").val(),
                        // status:$("#status").val()
                    },
                    success:function (data) {
                        if(data.code == 200){
                            housepaydata = data.data;
                            renderTemDetailTable(housepaydata);
                        }else{
                            layer.msg(data.msg, {
                                icon: 2,
                                time: 1000
                            });
                        }
                    }
                }
            );
            //标注选中样式
            obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
        });
        table.on('rowDouble(TemTable)', function(obj){
            //TODO 双击加载数据
            var data = obj.data;
            var arr={};
            temitemjsonarray.length = 0;
            for(var i = 0;i<housepaydata.length;i++){
                arr={
                    "drugId":housepaydata[i].drugId,
                    "drugName":housepaydata[i].drugName,
                    "drugUnit":housepaydata[i].drugUnit,
                    "priceIn":housepaydata[i].price,
                    "drugNumber":housepaydata[i].number,
                    "remark":housepaydata[i].remark
                };
                temitemjsonarray.push(arr);
            }
            $('#tem_no').val(data.serialNo);
            $('#create_user').val(data.operator);
            $('#create_user_id').val(data.operator);
            $('#create_time').val(data.gmtCreate);
            // $('#should_pay').val(data.temTotalPay);
            $('#auditor').val(data.auditor);
            $('#auditingTime').val(data.auditingTime);
            start = 1;
            isadd = 1;
            if( data.status == 1 ){
                //TODO 已保存
                ispay = 1;
                $("#editPay").removeAttr('disabled');
                $("#StopTem").removeAttr('disabled');
                $("#Audit").removeAttr('disabled');
                $("#PrintTem").attr('disabled',true);
            }else if( data.status == 2 ){
                //TODO 已收费
                ispay = 2;
                $("#editPay").attr('disabled',true);
                $("#Audit").attr('disabled',true);
                $("#StopTem").removeAttr('disabled');
                $("#PrintTem").removeAttr('disabled');
            }else if( data.status == '-1' ){
                //TODO 已作废
                ispay = 3;
                $("#editPay").attr('disabled',true);
                $("#StopTem").attr('disabled',true);
                $("#PrintTem").attr('disabled',true);
                $("#Audit").attr('disabled',true);
            }
            $("#savePay").attr('disabled',true);
            $("#drug_jm").attr('disabled',true);
            $("#in_price").attr('disabled',true);
            $("#drug_number").attr('disabled',true);

            renderPro2(temitemjsonarray);
            $('#HousepayForm').modal('hide');
            // renderTemItem('tem_item_id');
            renderProevent();
        });
    }



    $("#btnSearchTem").click(function() {
        //TODO 查询单据
        SearchTem();
    });



    function SearchTem(){
        //TODO 查询单据
        $.bootstrapLoading.start({loadingTips: "请等待..."});
        // CheckSession();
        setTimeout(function (){
            $.ajax(
                {
                    type: "get",
                    async: false,
                    url: "/drug-input-output/listBySerialNO",
                    data: {
                        serialNo:'RK20200403172014519'
                        // startday:$("#startday").val(),
                        // endday:$("#endday").val(),
                        // status:$("#status").val()
                    },
                    success:function (data) {
                        $.bootstrapLoading.endLoading();
                        housejsonarray = data.data;
                        renderTemTable(housejsonarray);
                        renderTemTableevent();
                        renderTemDetailTable(emptyjsonarray);
                    }
                }
            )
        },200);
    }



    function initpay(){
        //TODO 加载单据弹出层
        $('#HousepayForm').modal('show');
        renderTemTable(emptyjsonarray);
        renderTemDetailTable(emptyjsonarray);
        var endmon = GetDate().split('-')[0] + '-' + GetDate().split('-')[1] + '-01';
        var date=new Date(endmon);      //计算当月最后一天
        var startday = getNowFormatDate(date);
        var endday = startday.split('-')[0] + '-' + startday.split('-')[1] + '-'+getLastDay(startday.split('-')[0],startday.split('-')[1]);
        $("#startday").val(startday);
        $("#endday").val(endday);
        // $('#startday').val();
        SearchTem();
        form.render();
    }


    $('#btnSearch').click(function(event) {
        //TODO 弹出双表、初始化
        initpay();
    });

    $('#StopTem').click(function(event) {
        //TODO 作废单据
        $('#StopReasonForm').modal('show');
        $('.tem_no').val( $('#tem_no').val() );
        $('.get_pay').val( $('#should_pay').val() );
        $('.payType').val(payType);
        $('#stop_reason').val('').focus()
    });

    $('#PrintTem').click(function(event) {
        //TODO 打印单据
        openprint( $('#tem_no').val() )
    });


    $("#btnStopReasonForm").click(function () {
        //TODO 确认作废
        CheckSession();
        if ($('#stop_reason').val() == '' || $('#stop_reason').val() == undefined) {
            layer.msg('请填写作废原因', {
                icon: 5,
                time: 1000
            });
            $('#stop_reason').focus()
        } else {
            layer.confirm('确认要作废吗？', function (index) {
                $.ajax(
                    {
                        type: "post",
                        async: false,
                        url: "/Manage/addManageStopback",
                        data: {
                            payNo:$('#tem_no').val(),
                            type:'临时收费作废',
                            stopbackReason:$('#stop_reason').val()
                        },
                        success:function (res) {
                            if(res.status==200){
                                if( $('.payType').val() == '微信支付' ){
                                    $.ajax(
                                        {
                                            type: "post",
                                            async: false,
                                            url: "/wxpayApi/refundPayForWeb",
                                            data: {
                                                outTradeNo:$('#tem_no').val(),
                                                refund_fee:$('.get_pay').val()*100
                                                // refund_fee:1
                                            },
                                            success:function (res) {
                                                if(res.status==200){
                                                    StopTem();
                                                }else{
                                                    layer.msg(res.msg, {
                                                        icon: 2,
                                                        time: 1000
                                                    });
                                                }
                                            }
                                        }
                                    )
                                }else if( $('.payType').val() == '支付宝' ){
                                    $.ajax(
                                        {
                                            type: "post",
                                            async: false,
                                            url: "/alipay/trade_refund",
                                            data: {
                                                out_trade_no:$('#tem_no').val(),
                                                refund_amount:$('.get_pay').val()
                                            },
                                            success:function (res) {
                                                if(res.status==200){
                                                    StopTem();
                                                }else{
                                                    layer.msg(res.msg, {
                                                        icon: 2,
                                                        time: 1000
                                                    });
                                                }
                                            }
                                        }
                                    )
                                }
                                else{
                                    StopTem();
                                }
                            }else{
                                layer.msg(res.msg, {
                                    icon: 2,
                                    time: 1000
                                });
                            }
                        }
                    }
                )
            });
        }
    });



    function StopTem(){
        //TODO 作废单据
        $.ajax(
            {
                type: "post",
                async: false,
                url: "/Manage2/updateTemPaymentFlow",
                data: {
                    tem_no:$('#tem_no').val(),
                    cancelman:username,
                    canceltime:CurentTime() + ':00',
                    status:2
                },
                success:function (res) {
                    if(res.status==200){
                        layer.msg('已作废', {
                            icon: 1,
                            time: 1000
                        });
                        $('#StopReasonForm').modal('hide');
                        ispay = 3;
                        isadd = 1;
                        $("#editPay").attr('disabled',true);
                        $("#savePay").attr('disabled',true);
                        $("#StopTem").attr('disabled',true);
                        $("#PrintTem").attr('disabled',true);
                    }else{
                        layer.msg(res.msg, {
                            icon: 2,
                            time: 1000
                        });
                    }
                }
            }
        )
    }



    $(".get_pay").bind("input propertychange",function(event){
        //TODO 计算找回金额
        if( $('.get_pay').val() == ''){
            $('.back_pay').text(0)
        }else{
            var back_pay = parseFloat( parseFloat( $('.get_pay').val() ) - parseFloat( $('.should_pay').text() ) ).toFixed(2);
            if(back_pay.split('.')[1] == 00 ){
                back_pay = parseInt(back_pay);
            }else{
                back_pay = back_pay
            }
            $('.back_pay').text( back_pay );
        }
    });




    $('#addPay').click(function(event) {
        //TODO 添加单据
        if( $('#tem_no').val() == '' || $('#tem_no').val() == undefined){
            addpay();
        }else{
            layer.confirm('重新新增单据前，数据将重置，请确认已保存现有单据。', function(index) {
                addpay(index);
            });
        }
    });



    $('#editPay').click(function(event) {
        //TODO 修改单据
        start = 1;
        isadd = 0;
        renderPro(temitemjsonarray);
        $("#drug_jm").removeAttr('disabled');
        $("#in_price").removeAttr('disabled');
        $("#drug_number").removeAttr('disabled');
        $("#savePay").removeAttr('disabled');
        $("#editPay").attr('disabled',true);
        $("#addTemItem").removeAttr('disabled');
        renderJm();
        renderClose();
        renderInpriceKeyDown();
        renderDrugNumberKeyDown();
        renderProevent();
    });



    function addpay(index){
        //TODO 添加单据
        start = 0;
        isadd = 0;
        ispay = 0;
        temitemjsonarray.length = 0;
        renderPro(emptyjsonarray);
        renderJm();
        renderClose();
        renderInpriceKeyDown();
        renderDrugNumberKeyDown();
        $('#create_user').val(name);
        $('#create_time').val(CurentTime());
        $('#create_user_id').val(username);
        var tem_no = 'RK'+writeCurrentDate().replace(" ", "").replace("-","").replace(":","").replace("-","").replace(":","") + randomNum(100,999);
        $('#tem_no').val(tem_no);
        // $('#type').val('入库');
        $("#drug_jm").removeAttr('disabled').focus().val('');
        $("#in_price").removeAttr('disabled').val('');
        $("#drug_number").removeAttr('disabled').val('');
        $("#drug_name").val('');
        $("#drug_specifications").val('');
        form.render('select', 'sel_srf');
        // $("#addTemItem").removeAttr('disabled');
        // $("#btnPay").removeAttr('disabled');

        $('#should_pay').val('');
        $("#StopTem").attr('disabled',true);
        $("#PrintTem").attr('disabled',true);
        $("#Audit").removeAttr('disabled',true);
        $("#savePay").removeAttr('disabled');


        // $('.out_should_pay').text(0);
        // disTemItem();
        // renderProevent();
        if( index != ''){
            layer.close(index);
        }
    }



    function renderJm(){
        //TODO 渲染简码事件
        $("#drug_jm").on("input propertychange",function(e){
            //TODO 药品查询事件
            renderdruglist('');
            renderdrugevent();
            if($('#drug_jm').val()==""){
                $("#FormDrug").css('display','none');
                renderdruglist(drugdata);
            }else{
                $("#FormDrug").css('display','block');
                renderdruglist('');
                var cookjsonstr="[]";
                var cookjsonarray = eval('('+cookjsonstr+')');
                var srf = $('#srf').val();
                switch(srf) {
                    case 'wb':
                        var count = 0;
                        for (var i = 0; i < drugdata.length; i++) {
                            if (drugdata[i].wb.indexOf($("#drug_jm").val()) >= 0 ) {
                                count = count + 1;
                                var arr = drugdata[i];
                                cookjsonarray.push(arr);
                                table.reload('DrugList', {
                                    data: cookjsonarray
                                });
                            }
                        }
                        if(count == 0){
                            table.reload('DrugList', {
                                data: emptyjsonarray
                            });
                        }
                        rowindex = cookjsonarray.length;
                        break;
                    case 'zdy':
                        var count = 0;
                        for (var i = 0; i < drugdata.length; i++) {
                            if (drugdata[i].zdy.indexOf($("#drug_jm").val()) >= 0 ) {
                                count = count + 1;
                                var arr = drugdata[i];
                                cookjsonarray.push(arr);
                                table.reload('DrugList', {
                                    data: cookjsonarray
                                });
                            }
                        }
                        if(count == 0){
                            table.reload('DrugList', {
                                data: emptyjsonarray
                            });
                        }
                        rowindex = cookjsonarray.length;
                        break;
                    case 'py':
                        var count = 0;
                        for (var i = 0; i < drugdata.length; i++) {
                            if (drugdata[i].py.indexOf($("#drug_jm").val()) >= 0 ) {
                                count = count + 1;
                                var arr = drugdata[i];
                                cookjsonarray.push(arr);
                                table.reload('DrugList', {
                                    data: cookjsonarray
                                });
                            }
                        }
                        if(count == 0){
                            table.reload('DrugList', {
                                data: emptyjsonarray
                            });
                        }
                        rowindex = cookjsonarray.length;
                        break;
                }
            }
        });
    }



    function renderInpriceKeyDown(){
        //TODO 入库价回车事件
        $('#in_price').bind('keydown', function (e) {
                var key = e.which;
                if (key == 13) {
                    if( $("#in_price").val() == '' || $("#in_price").val() == 0 ){
                        layer.msg('写输入入库价', {
                            icon: 5,
                            time: 1000
                        });
                    }else{
                        $("#drug_number").focus();
                    }
                }
            }
        );
    }


    function renderDrugNumberKeyDown(){
        //TODO 入库数量回车事件
        $('#drug_number').bind('keydown', function (e) {
                var key = e.which;
                if (key == 13) {
                    if( $("#drug_number").val() == '' || $("#drug_number").val() == 0 ){
                        layer.msg('写输入入库数量', {
                            icon: 5,
                            time: 1000
                        });
                    }else{
                        var drug_id = $('#drug_id').val();
                        var drug_name = $('#drug_name').val();
                        var drug_specifications = $('#drug_specifications').val();
                        var in_price = $('#in_price').val();
                        var drug_number = $('#drug_number').val();
                        var drug_unit = $('#drug_unit').val();
                        var arr={};
                        arr={
                            "drugId":drug_id ,
                            "drugName":drug_name ,
                            "drugSpecifications":drug_specifications ,
                            "priceIn":in_price,
                            "drugNumber":drug_number,
                            "drugUnit":drug_unit,
                            "remark":''
                        };
                        temitemjsonarray.push(arr);
                        renderPro(temitemjsonarray);
                        renderProevent();
                        $("#drug_jm").removeAttr('disabled').val('').focus();
                        $("#in_price").removeAttr('disabled').val('');
                        $("#drug_number").removeAttr('disabled').val('');
                        index = 0;      //初始化简码表格
                        renderJm();
                        renderClose();
                        renderInpriceKeyDown();
                        renderDrugNumberKeyDown();
                    }
                }
            }
        );
    }




    function sumpay(){
        //TODO 计算单据合计
        should_pay = 0;
        for(var i = 0;i<temitemjsonarray.length;i++){
            //TODO 计算单据合计
            should_pay = should_pay + parseFloat(temitemjsonarray[i].priceIn) * parseFloat(temitemjsonarray[i].drugNumber)
        }
        should_pay = parseFloat(should_pay).toFixed(2);
        if(should_pay.split('.')[1] == 00 ){
            should_pay = parseInt(should_pay);
        }else{
            should_pay = should_pay
        }
        return should_pay

    }



    $('#savePay').click(function(event) {
        //TODO 保存单据
        // CheckSession();
        if(sumpay() == 'NaN' || sumpay() == 0){
            layer.msg('项目费用有误，请检查', {
                icon: 2,
                time: 1000
            });
        }else{
            $('#should_pay').val(sumpay());
            if(CheckComplete()==true){
                if( temitemjsonarray.length == 0){
                    layer.msg('无收费项目', {
                        icon: 2,
                        time: 1000
                    });
                }else{
                    if( start == 0 ){
                        //TODO 新增单据
                        if( addtem() == true ){
                            layer.msg('保存成功', {
                                icon: 6,
                                time: 1000
                            });
                            $("#drug_jm").attr('disabled',true);
                            $("#in_price").attr('disabled',true);
                            $("#drug_number").attr('disabled',true);
                            $("#savePay").attr('disabled',true);
                            isadd = 1;
                            ispay = 1;
                            renderPro2(temitemjsonarray);
                            $("#editPay").removeAttr('disabled');
                            $("#StopTem").removeAttr('disabled');
                            $("#PrintTem").attr('disabled',true);
                        }
                    }else if ( start == 1 ){
                        //TODO 修改保存单据
                        if( edittem() == true ){
                            layer.msg('保存成功', {
                                icon: 6,
                                time: 1000
                            });
                            isadd = 1;
                            ispay = 1;
                            $("#target_id").attr('disabled',true);
                            form.render('select', 'sel_target');
                            $("#contacts").attr('disabled',true);
                            $("#phone").attr('disabled',true);
                            $("#tem_house_no").attr('disabled',true);
                            $("#remark").attr('disabled',true);
                            $("#savePay").attr('disabled',true);
                            renderPro2(temitemjsonarray);
                            $("#editPay").removeAttr('disabled');
                            $("#StopTem").removeAttr('disabled');
                            $("#PrintTem").attr('disabled',true);
                        }
                    }
                }
            }else{
                return false;
            }
        }

    });


    function addtem() {
        //TODO 新增单据
        var bRet = true;
        var count = 0;
        for(var i = 0;i<temitemjsonarray.length;i++){
            $.ajax(
                {
                    type: "post",
                    async: false,
                    url: "/drug-input-output/insert",
                    data: {
                        serialNo:$('#tem_no').val(),
                        type:'入库',
                        drugId:parseInt(temitemjsonarray[i].drugId),
                        drugName:temitemjsonarray[i].drugName,
                        drugSpecifications:temitemjsonarray[i].drugSpecifications,
                        drugUnit:temitemjsonarray[i].drugUnit,
                        price:parseInt(temitemjsonarray[i].priceIn),
                        number:parseInt(temitemjsonarray[i].drugNumber),
                        remark:temitemjsonarray[i].remark,
                        gmtCreate:$('#create_time').val() + ':00',
                        operator:$('#create_user_id').val(),
                        status:1
                    },
                    success:function (res) {
                        if(res.code==200){
                            // bRet = true;
                            count = count + 1;
                        }else{
                            layer.msg(res.msg, {
                                icon: 2,
                                time: 1000
                            });
                            // bRet = false
                        }
                    }
                }
            )
        }
        if( count == temitemjsonarray.length ){
            bRet = true;
        }else{
            bRet = false
        }
        return bRet;
    }



    function edittem() {
        //TODO 修改保存单据
        var bRet = true;
        $.ajax(
            {
                type: "post",
                async: false,
                url: "/Manage2/updateTemPaymentFlow",
                data: {
                    tem_no:$('#tem_no').val(),
                    type_id:1,
                    tem_total_pay:$('#should_pay').val(),
                    contacts:$('#contacts').val(),
                    phone:$('#phone').val(),
                    target_id:$('#target_id').val(),
                    house_no:$('#tem_house_no').val(),
                    remark:$('#remark').val()
                },
                success:function (res) {
                    if(res.status==200){
                        $.ajax(
                            {
                                type: "post",
                                async: false,
                                url: "/Manage2/deleteTemPaymentDetail",
                                data: {
                                    tem_no:$('#tem_no').val()
                                },
                                success:function (res) {
                                    if(res.status==200){
                                        $.ajax(
                                            {
                                                type: "post",
                                                async: false,
                                                url: "/Manage2/insertTemPaymentDetail",
                                                data: {
                                                    tem_no:$('#tem_no').val(),
                                                    json:JSON.stringify(temitemjsonarray)
                                                },
                                                success:function (res) {
                                                    if(res.status==200){
                                                        bRet = true;
                                                    }else{
                                                        layer.msg(res.msg, {
                                                            icon: 2,
                                                            time: 1000
                                                        });
                                                        bRet = false
                                                    }
                                                }
                                            }
                                        )
                                    }else{
                                        layer.msg(res.msg, {
                                            icon: 2,
                                            time: 1000
                                        });
                                        bRet = false
                                    }
                                }
                            }
                        )
                    }else{
                        layer.msg(res.msg, {
                            icon: 2,
                            time: 1000
                        });
                        bRet = false
                    }
                }
            }
        );
        return bRet;
    }




    function openprint(tem_no) {
        //TODO 打印收据
        layer.confirm('是否打印收据', function(index) {
            window.open('tempayment-print.html?tem_no='+tem_no);
            layer.closeAll('dialog');
        });
    }



    function CheckComplete(){
        //TODO 检查信息填写完整性
        var sRet='';
        var aRet='';
        var bRet=true;
        if($('#tem_no').val()==''||$('#tem_no').val()==undefined){
            sRet='单据号';
            aRet='tem_no';
        }else if($('#create_user_id').val()==''||$('#create_user_id').val()==undefined){
            sRet='创建者';
            aRet='create_user_id';
        }else if($('#create_time').val()==''||$('#create_time').val()==undefined){
            sRet='创建时间';
            aRet='create_time';
        }else if($('#should_pay').val()==''||$('#should_pay').val()==undefined){
            sRet='单据合计';
            aRet='should_pay';
        }
        if(sRet!=''){
            layer.msg(sRet+'信息有误！请检查', {
                icon: 5,
                time: 1000
            });
            $('#'+aRet).focus();
            $('#'+aRet).addClass('layui-form-danger');
            bRet=false;
        }

        return bRet;
    }




    $(document).on('keydown','#drug_jm',function (e) {
        //TODO 简码药品表格键盘快捷键
        var quickclick = $('#FormDrug').find('.panel-body').find('.layui-table-view').find('.layui-table-main').find('.layui-table').find("tr:last");
        switch (event.keyCode) {
            case 40://down
                var tr = $('#FormDrug').find('.panel-body').find('.layui-table-view').find('.layui-table-main').find('.layui-table').find("tr:eq(" + index + ")");
                tr.css('background-color', 'white').css('color','#666');
                if (index >= rowindex - 1) {
                    tr = $('#FormDrug').find('.panel-body').find('.layui-table-view').find('.layui-table-main').find('.layui-table').find("tr:eq(" + index + ")");
                    tr.css('background-color', '#009688').css('color','#FFFFFF');
                    break;
                } else {
                    index += 1;
                    tr = $('#FormDrug').find('.panel-body').find('.layui-table-view').find('.layui-table-main').find('.layui-table').find("tr:eq(" + index + ")");
                    tr.css('background-color', '#009688').css('color','#FFFFFF');
                    break;
                }
            case 38://up
                var tr = $('#FormDrug').find('.panel-body').find('.layui-table-view').find('.layui-table-main').find('.layui-table').find("tr:eq(" + index + ")");
                tr.css('background-color', 'white').css('color','#666');
                if (index <= 0) {
                    tr = $('#FormDrug').find('.panel-body').find('.layui-table-view').find('.layui-table-main').find('.layui-table').find("tr:eq(" + index + ")");
                    tr.css('background-color', '#009688').css('color','#FFFFFF');
                    break;
                } else {
                    index -= 1;
                    tr = $('#FormDrug').find('.panel-body').find('.layui-table-view').find('.layui-table-main').find('.layui-table').find("tr:eq(" + index + ")");
                    tr.css('background-color', '#009688').css('color','#FFFFFF');
                    break;
                }
            case 13://Enter
                var tr = $('#FormDrug').find('.panel-body').find('.layui-table-view').find('.layui-table-main').find('.layui-table').find("tr:eq(" + index + ")");
                var td = tr.find('td');
                var obj = {};
                for (var i = 0; i < td.length; i++) {
                    obj[$(td[i]).attr('data-field')] = $(td[i]).find('div').text();
                }
                //console.log(obj);
                $("#drug_name").val(obj.drugName);
                $("#drug_specifications").val(obj.drugSpecifications);
                $("#drug_id").val(obj.drugId);
                $("#drug_unit").val(obj.drugUnit);
                $("#in_price").val(obj.priceIn).focus();
                $("#drug_jm").val('');
                $("#FormDrug").css('display', 'none');
            case 8://BackSpace BackSpace
                break;
        }
    })




    function renderClose(){
        $('.closes,.close').click(function(event) {
            //TODO 关闭动态框
            $(this).parent().parent().css('display','none');
            // clearInterval(iCount);
        });
    }



});


